package cn.jtfadmin.base.lang.common.domain.entity;


import cn.jtfadmin.base.lang.enums.BooleanEnum;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 内置实体监听器<br/>
 * 内置实体不能移除，由实体监听调用
 *
 * @author jtf
 * @since 0.0.1
 * @see BuildInAbleEntity
 * @see BuildInEntityDelValidUtils
 */
@Component
public class BuildInAbleEntityListener implements EntityListener {


    /**
     * 设置是否内置
     *
     * @param object 实体 必须是 BuildInAbleEntity
     */
    public void prePersist(Object object) {
        if (object instanceof BuildInAbleEntity) {
            BuildInAbleEntity entity = (BuildInAbleEntity) object;
            BooleanEnum buildInFlag = entity.getBuildInFlag();
            if (Objects.isNull(buildInFlag)) {
                entity.setBuildInFlag(BooleanEnum.FALSE);
            }
        }
    }

    @Override
    public void preRemove(Object object) {
        if (object instanceof BuildInAbleEntity) {
            BuildInAbleEntity entity = (BuildInAbleEntity) object;
            BooleanEnum buildInFlag = entity.getBuildInFlag();
            if (!BuildInEntityDelValidUtils.isAllowDel() && Objects.equals(buildInFlag, BooleanEnum.TRUE)) {
                throw new RuntimeException("系统组件,不允许删除");
            }

        }
    }
}
